﻿@inherits BaseComponent

<LoginInfoForm @ref="form" Model="Model">
    <FormItem Label="" Required Rules="@Context.RuleRequired("PhoneNo")">
        <AntInput @bind-Value="@context.PhoneNo" Placeholder="@Language["PhoneNo"]">
            <Prefix><Icon Type="phone" /></Prefix>
        </AntInput>
    </FormItem>
    <FormItem Label="" Required Rules="@Context.RuleRequired("PhoneCode")">
        <AntCaptcha @bind-Value="@context.PhoneCode" Placeholder="@Language["PhoneCode"]" Option="option">
            <Prefix><Icon Type="lock" /></Prefix>
        </AntCaptcha>
    </FormItem>
    <FormItem Label="" Required Rules="@Context.RuleRequired("Captcha")">
        <AntCaptcha @ref="captcha" @bind-Value="@context.Captcha" Placeholder="@Language["Captcha"]">
             <Prefix><Icon Type="check" /></Prefix>
        </AntCaptcha>
    </FormItem>
    <FormItem>
        <Switch @bind-Value="@context.Remember" /> @Language["Login.RememberPhone"]
    </FormItem>
    <FormItem>
        <Button Type="@ButtonType.Primary" Block OnClick="OnPhoneLogin">@Language["Login"]</Button>
    </FormItem>
</LoginInfoForm>

@code {
    private LoginInfoForm form;
    private AntCaptcha captcha;
    private CaptchaOption option = new CaptchaOption { SMSCount = 60 };

    [Parameter] public LoginFormInfo Model { get; set; }
    [Parameter] public Func<string, Task<Known.Result>> OnSendSMS { get; set; }
    [Parameter] public Func<Task> OnLogin { get; set; }

    protected override async Task OnInitAsync()
    {
        await base.OnInitAsync();
        option.SMSAction = () =>
        {
            if (string.IsNullOrWhiteSpace(Model.PhoneNo))
                return Known.Result.ErrorAsync(Language.Required("PhoneNo"));
            if (string.IsNullOrWhiteSpace(Model.Captcha))
                return Known.Result.ErrorAsync(Language.Required("Captcha"));
            if (!captcha.Validate(out string message))
                return Known.Result.ErrorAsync(message);

            return OnSendSMS?.Invoke(Model.PhoneNo);
        };
    }

    private async Task OnPhoneLogin()
    {
        if (!form.Validate())
            return;

        Model.IsMobile = Context.IsMobile;
        await OnLogin?.Invoke();
    }
}